using UnityEngine;
using System.Collections;

public class DirectionChangeVolume : MonoBehaviour
{
	private enum Dir
	{
		DIR_UP,
		DIR_LEFT,
		DIR_DOWN,
		DIR_RIGHT,
		DIR_NONE
	}
	private Dir direction = Dir.DIR_NONE;
	
	// Use this for initialization
	void Start ()
	{
		if (name == "Left")
			direction = Dir.DIR_LEFT;
		else if (name == "Right")
			direction = Dir.DIR_RIGHT;
		else if (name == "Top")
			direction = Dir.DIR_UP;
		else if (name == "Bottom")
			direction = Dir.DIR_DOWN;
		
//		if (transform.Find ("Left") != null)
//			direction = Dir.DIR_LEFT;
//		else if (transform.Find ("Right") != null)
//			direction = Dir.DIR_RIGHT;
//		else if (transform.Find ("Up") != null)
//			direction = Dir.DIR_UP;
//		else if (transform.Find ("Down") != null)
//			direction = Dir.DIR_DOWN;
		
		Debug.Log (direction);
		
		rigidbody.freezeRotation = true;
	}
	
	// Update is called once per frame
	void Update ()
	{
	
	}
	
	void OnTriggerEnter(Collider collision)
	{
		ChangeCube(collision.transform);
	}
	
	private void ChangeCube(Transform inCube)
	{
		Cube thisCube = inCube.GetComponent<Cube>();
		if (thisCube == null)
			return;
		
		float spd = thisCube.CubeSpeed;
		Vector2 dir = new Vector2(0,0);
		
		if (thisCube.IsClockWise)
		{
			if (direction == Dir.DIR_LEFT)
			{
				dir.x = 0;
				dir.y = spd;
			}
			else if (direction == Dir.DIR_RIGHT)
			{
				dir.x = 0;
				dir.y = -spd;
			}
			else if (direction == Dir.DIR_UP)
			{
				dir.x = spd;
				dir.y = 0;
			}
			else if (direction == Dir.DIR_DOWN)
			{
				dir.x = -spd;
				dir.y = 0;
			}
		}
		else
		{
			if (direction == Dir.DIR_LEFT)
			{
				dir.x = 0;
				dir.y = -spd;
			}
			else if (direction == Dir.DIR_RIGHT)
			{
				dir.x = 0;
				dir.y = spd;
			}
			else if (direction == Dir.DIR_UP)
			{
				dir.x = -spd;
				dir.y = 0;
			}
			else if (direction == Dir.DIR_DOWN)
			{
				dir.x = spd;
				dir.y = 0;
			}
		}
		
		thisCube.CubeVelocity = dir;
	}
	
	void OnCollisionEnter(Collision collision)
	{
		Cube thisCube = collision.transform.GetComponent<Cube>();
		if (thisCube == null)
			return;
		
		float spd = thisCube.CubeSpeed;
		Vector2 dir = new Vector2(0,0);
		
		if (thisCube.IsClockWise)
		{
			if (direction == Dir.DIR_LEFT)
			{
				dir.x = 0;
				dir.y = spd;
			}
			else if (direction == Dir.DIR_RIGHT)
			{
				dir.x = 0;
				dir.y = -spd;
			}
			else if (direction == Dir.DIR_UP)
			{
				dir.x = spd;
				dir.y = 0;
			}
			else if (direction == Dir.DIR_DOWN)
			{
				dir.x = -spd;
				dir.y = 0;
			}
		}
		else
		{
			if (direction == Dir.DIR_LEFT)
			{
				dir.x = 0;
				dir.y = -spd;
			}
			else if (direction == Dir.DIR_RIGHT)
			{
				dir.x = 0;
				dir.y = spd;
			}
			else if (direction == Dir.DIR_UP)
			{
				dir.x = -spd;
				dir.y = 0;
			}
			else if (direction == Dir.DIR_DOWN)
			{
				dir.x = spd;
				dir.y = 0;
			}
		}
		
		thisCube.CubeVelocity = dir;
	}
}

